import { defineStore } from 'pinia';
import type { AppState } from './types';
import type { RouteRecordRaw, RouteRecordNormalized } from 'vue-router';
import { useLocalStorage } from '@vueuse/core';
import { getRoutes } from '@/api/system/system';
import { regexUrl } from '@/utils';
const NotFoundPage = () => import('@/views/not-found/index.vue');
const viewsModules: Record<string, unknown> = import.meta.glob('@/views/**/*.{vue,tsx}', {
  eager: true,
});

const loadView = (path: string = '') => {
  for (const key in viewsModules) {
    const dir = key.split('views/')[1].replace(/^(.*)\.(vue|tsx)$/, '$1');
    if (path === dir) {
      return () => viewsModules[key];
    }
  }
  return NotFoundPage;
};

function filterChildren(childrenMap: any[], lastRouter: any = false) {
  let children: any[] = [];
  childrenMap.forEach((el) => {
    el.path = lastRouter ? lastRouter.path + '/' + el.path : el.path;
    if (el.children && el.children.length && el.component === 'ParentView') {
      children = children.concat(filterChildren(el.children, el));
    } else {
      children.push(el);
    }
  });
  return children;
}

// 转换服务端路由配置
const transformServerRoutes = (
  asyncRouterMap: any[],
  parentPath: string = '',
  type: boolean = false,
): RouteRecordRaw[] => {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = DEFAULT_LAYOUT;
      } else {
        route.component = loadView(route.component);
      }
    }
    let resolvedPath = route.path;
    if (!regexUrl.test(resolvedPath)) {
      // 顶级路由必须用绝对路径
      if (!parentPath && !resolvedPath.startsWith('/')) {
        resolvedPath = `/${resolvedPath}`;
      }
      // 嵌套路由使用相对路径
      if (parentPath) {
        resolvedPath = `${parentPath}/${resolvedPath}`.replace(/\/+/g, '/');
      }
    }
    route.path = resolvedPath;
    if (route.children != null && route.children && route.children.length) {
      route.children = transformServerRoutes(route.children, resolvedPath, type);
    } else {
      delete route['children'];
      delete route['redirect'];
    }
    return true;
  });
};

const useAppStore = defineStore('app', {
  state: (): AppState => ({
    colorWeak: false,
    navbar: true,
    menu: true,
    topMenu: false,
    hideMenu: false,
    menuCollapse: false,
    footer: true,
    themeColor: '#165DFF',
    menuWidth: 220,
    globalSettings: false,
    device: 'desktop',
    tabBar: false,
    menuFromServer: true,
    serverMenu: [],
    theme: useLocalStorage<'light' | 'dark' | 'system'>('arco-theme', 'dark'),
  }),
  getters: {
    appCurrentSetting(state: AppState): AppState {
      return { ...state };
    },
    appDevice(state: AppState) {
      return state.device;
    },
    appAsyncMenus(state: AppState): RouteRecordNormalized[] {
      return state.serverMenu as unknown as RouteRecordNormalized[];
    },
  },
  actions: {
    updateSettings(partial: Partial<AppState>) {
      this.$patch((state) => {
        Object.assign(state, partial);
      });
    },
    setTheme(mode: 'light' | 'dark' | 'system') {
      this.theme = mode;
    },
    toogleThmeColor(color: string) {
      this.themeColor = color;
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value;
    },
    async fetchServerMenuConfig(): Promise<RouteRecordRaw[]> {
      try {
        const res = await getRoutes();
        const { code, result } = res.data;
        if (code === 200) {
          console.log(result);
          this.serverMenu = [
            {
              path: '/',
              meta: {
                title: '首页',
                icon: 'icon-heart-fill',
              },
            },
          ];

          const dynamicRoutes = transformServerRoutes(result, '', true);
          addDynamicRoutes(router, dynamicRoutes);
        }
        return [];
      } catch (error) {
        console.error('获取服务端菜单失败:', error);
        this.serverMenu = [];
        return [];
      }
    },
    clearServerMenu() {
      this.serverMenu = [];
    },
  },
});

export default useAppStore;
